package com.yanqu.road.server.manger.activity.shuihuyezicard;


import com.yanqu.road.entity.activity.shuihuyezipai.*;
import com.yanqu.road.entity.activity.shuihuyezipai.config.*;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogShuiHuYeZiCardBattlerResultRecord;
import com.yanqu.road.entity.log.LogShuiHuYeZiCardPVEBattlerRoundRecord;
import com.yanqu.road.entity.log.LogShuiHuYeZiCardUserCard;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.ShuiHuYeZiCardProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.shuihuyezicard.ShuiHuYeZiCardModule;
import com.yanqu.road.server.manger.AbstractShuiHuYeZiCardRoom;
import com.yanqu.road.server.manger.ShuiHuYeZiCardCommonMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;

/**
 * @Description 水浒叶子牌 pve房间
 * @Author cwq
 * @Data 2021/12/8 11:19
 */
public class ShuiHuYeZiCardPVERoom extends AbstractShuiHuYeZiCardRoom {

    /**
     * 玩家当前出的卡牌
     */
    private ShuiHuYeZiCardBattleCard cardBattleCard;

    /**
     * 是否是引导房间
     */
    private boolean isGuide = false;

    public ShuiHuYeZiCardPVERoom(ShuiHuYeZiCardRoomData roomInfo) {
        super(roomInfo);
    }

    public ShuiHuYeZiCardPVERoom(ShuiHuYeZiCardRoomData roomInfo, boolean isGuide) {
        super(roomInfo);
        this.isGuide = isGuide;
    }

    @Override
    public boolean startGame() {
        if(isGuideRoom()){
            // 练习模式 的引导房间
            creatGuideRoom();
        }else {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(getRoomInfo().getUserId());
            ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
            getRoomInfo().setRound(1);
            getRoomInfo().setStartTime(DateHelper.getCurrentTime());
            // 选择 ai 模型
            int aiModelIndex = chooseAiModelIndex(shuiHuYeZiCardModule);
            getRoomInfo().setAiModelIndex(aiModelIndex);
            List<List<Integer>> cardList = dealCard(ShuiHuYeZiCardMgr.getConfig());
            Map<Integer, ShuiHuYeZiCardBattleCard> cardMap1 = ShuiHuYeZiCardCommonMgr.createBattleCard(cardList.get(0), shuiHuYeZiCardModule.getUserData().getCardMap());

            // 随机ai手里的卡牌
            Map<Integer, ShuiHuYeZiCardUserCard> aiCardMap = randomAiCardMap(shuiHuYeZiCardModule);
            Map<Integer, ShuiHuYeZiCardBattleCard> cardMap2 = ShuiHuYeZiCardCommonMgr.createBattleCard(cardList.get(1), aiCardMap);

            getRoomInfo().getUserCardMap().put(player.getUserId(), cardMap1);
            getRoomInfo().getUserCardMap().put((long)(getRoomInfo().getRoomId()), cardMap2);

            touchBuff(ShuiHuYeZiCardMgr.getConfig());
        }
        return true;
    }

    public void playCard(GamePlayer player, int id, int round) {
        ShuiHuYeZiCardProto.ShuiHuYeZiCardPlayCardRespMsg.Builder resp = ShuiHuYeZiCardProto.ShuiHuYeZiCardPlayCardRespMsg.newBuilder();
        int ret = playCard(player.getUserId(),id,round);
        resp.setRet(ret);
        player.sendPacket(ClientProtocol.U_SHUIHUYEZICARD_PLAY_CARD,resp);
        if(ret == 0){
            Map<Integer, ShuiHuYeZiCardBattleCard> npcCardMap = getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId()));
            Map<Integer, ShuiHuYeZiCardBattleCard> userCardMap = getRoomInfo().getUserCardMap().get(player.getUserId());
            cardBattleCard = userCardMap.get(id);
            int buffId = getRoomInfo().getBuffId();
            ShuiHuYeZiCardBattleCard npcPlayCard = null;
            if(isGuideRoom()){
                // 练习模式 中的引导
                npcPlayCard = guideRoomPlayCard();
            }
            if(npcPlayCard == null){
                npcPlayCard = autoPlayCard();
            }

            List<LogShuiHuYeZiCardUserCard> userCardList = ShuiHuYeZiCardCommonMgr.createLogShuiHuYeZiCardUserCardList(userCardMap);
            List<LogShuiHuYeZiCardUserCard> npcCardList = ShuiHuYeZiCardCommonMgr.createLogShuiHuYeZiCardUserCardList(npcCardMap);

            npcCardMap.remove(npcPlayCard.getId());
            userCardMap.remove(id);

            int curRound = getRoomInfo().getRound();
            long winnerId = battle(cardBattleCard,player.getUserId(),false,npcPlayCard,getRoomInfo().getRoomId(),false);

            // 加日志
            LogMgr.addLogShuiHuYeZiCardPVEBattlerRoundRecord(new LogShuiHuYeZiCardPVEBattlerRoundRecord(ShuiHuYeZiCardMgr.getActivityInfo().getActivityId(),getRoomInfo().getRoomId(),
                    getRoomInfo().getStartTime(),player.getUserId(),userCardList,cardBattleCard.getId(),getRoomInfo().getAiModelIndex(),npcCardList,
                    npcPlayCard.getId(),getRoomInfo().getBuffId(),winnerId,DateHelper.getCurrentSecond()));

            // 回合结束
            roundOver(ShuiHuYeZiCardMgr.getConfig());

            int roomType;
            if(getRoomInfo().getRoomId() == Integer.MAX_VALUE){
                roomType = 0;
            }else {
                roomType = 1;
            }

            ShuiHuYeZiCardProto.BroadcastShuiHuYeZiCardRespMsg.Builder broadcastType1 = builderRoundShuiHuYeZiCardRespMsg(curRound,winnerId,player.getUserId(),cardBattleCard,getRoomInfo().getRoomId(),npcPlayCard,0,buffId,roomType);
            // 广播 出牌情况
            player.sendPacket(ClientProtocol.U_SHUIHUYEZICARD_BROADCAST, broadcastType1);

            cardBattleCard = null;
            // 判断游戏是否结束
            endGame();
        }
    }

    @Override
    public int playCard(long userId, int id, int round) {
        if(getRoomInfo().getRound() != round){
            return GameErrorCode.E_SHUIHUYEZICARD_ACTIVITY_ROUND_ERROR;
        }
        Map<Integer, ShuiHuYeZiCardBattleCard> userCardMap = getRoomInfo().getUserCardMap().get(userId);

        if(!userCardMap.containsKey(id)){
            return GameErrorCode.E_SHUIHUYEZICARD_ACTIVITY_HAVE_NOT_THE_CARD;
        }

        return 0;
    }

    @Override
    public ShuiHuYeZiCardBattleCard autoPlayCard() {
        ShuiHuYeZiCardBattleCard playCard = null;
        playCard = noobAutoPlayCard();
        if(playCard != null){
            return playCard;
        }
        // 玩家 的手牌
        Map<Integer, ShuiHuYeZiCardBattleCard> userCardMap =  getRoomInfo().getUserCardMap().get(getRoomInfo().getUserId());
        // 玩家 每张牌出牌权重
        Map<Integer,Integer> userWeightMap = new HashMap<>();
        // npc 的手牌
        Map<Integer, ShuiHuYeZiCardBattleCard> npcCardMap =  getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId()));
        // npc 每张牌出牌权重
        Map<Integer,Integer> npcWeightMap = new HashMap<>();
//        getLogger().info("开始 计算出牌权重。userCardMap：{},npcWeightMap:{},buffId:{},nextBuffId:{}",userCardMap,npcCardMap,getRoomInfo().getBuffId(),getRoomInfo().getNextBuffId());
        for (int i = 0; i < 2; i++) {
            calPlayCardWeightMap(0,userCardMap,userWeightMap,npcCardMap,npcWeightMap);
            calPlayCardWeightMap(1,npcCardMap,npcWeightMap,userCardMap,userWeightMap);
//            getLogger().info("玩家当前的卡牌：{}，npc当前的卡牌：{}，玩家出牌的权重：{}。npc出牌的权重:{}",userCardMap.keySet(),npcCardMap.keySet(),userCardMap,npcWeightMap);
            if(i == 0){
                int X4 = ShuiHuYeZiCardMgr.getConfig().aiList.get(3);
                if(getRandom().nextInt(1000) >= X4){
                    // 有概率进行额外1次迭代计算
                    break;
                }
            }
        }
        // 3 AI 随机出一张卡牌
        List<PlayCardWeight> playCardWeightList = new ArrayList<>();
        for (Map.Entry<Integer,Integer> entry : npcWeightMap.entrySet()){
            playCardWeightList.add(new PlayCardWeight(entry.getKey(),entry.getValue()));
        }
        // 大到小 排序
        playCardWeightList.sort((t1,t2)->Integer.compare(t2.weight, t1.weight));

        int X2 = ShuiHuYeZiCardMgr.getConfig().aiList.get(1);
        // 向上取整
        int randomNum = (X2 * playCardWeightList.size() + 1000 - 1)/ 1000;

        int weightValue = 0;
        for (int i = 0; i < randomNum; i++) {
            weightValue += playCardWeightList.get(i).weight;
        }
        int randomValue = getRandom().nextInt(weightValue);
        for (int i = 0; i < randomNum; i++) {
            PlayCardWeight playCardWeight = playCardWeightList.get(i);
            if(randomValue < playCardWeight.weight){
                playCard = npcCardMap.get(playCardWeight.id);
                break;
            }
            randomValue -= playCardWeight.weight;
        }

        ShuiHuYeZiCardMgr.getLogger().info("出牌权重map :{},最终出牌：{}",playCardWeightList,playCard.getId());
        return playCard;
    }

    @Override
    public boolean isOver() {
        if (cardBattleCard == null) {
            for (Map<Integer, ShuiHuYeZiCardBattleCard> userCardMap : getRoomInfo().getUserCardMap().values()) {
                if (userCardMap.size() == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void endGame() {
        if (!isOver()) {
            return;
        }
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(getRoomInfo().getUserId());
        ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
        if(getRoomInfo().getRoomId() == Integer.MAX_VALUE){
            // 练习模式
            shuiHuYeZiCardModule.setExerciseRoom(null);
        }else {
            // npc 模式
            boolean isWin = false;
            String reward = null;
            ShuiHuYeZiCardRoomConfig roomConfig = ShuiHuYeZiCardMgr.getConfig().getRoomConfigMap().get(getRoomInfo().getRoomId());
            //  参赛时的段位
            int level = ShuiHuYeZiCardCommonMgr.getLevel(ShuiHuYeZiCardMgr.getConfig(),getRoomInfo().getRankScore());
            ShuiHuYeZiCardLevelConfig levelConfig = ShuiHuYeZiCardMgr.getConfig().getLevelConfigMap().get(level);

            int addRankScore = 0;
            // 原来的段位积分
            int oldRankScore = shuiHuYeZiCardModule.getUserData().getRankScore();
            isWin = isWin(getRoomInfo().getUserId());
            shuiHuYeZiCardModule.addBattleWinLose(getRoomInfo().getRankScore(),isWin,true,getRoomInfo().getAiModelIndex(),getRoomInfo().getRoomId());
            int winStreakNumPlus = 0;
            int remainCardPlus = 0;
            if(isWin){
                // 获胜
                addRankScore = levelConfig.getSucceedScore() * roomConfig.getScoreParam();
                reward = roomConfig.getSucceedReward();
                // 额外的分数加成
                ShuiHuYeZiCardCalExtraResult result = ShuiHuYeZiCardMgr.calExtraRankScore(shuiHuYeZiCardModule.getUserData().getPveWinningStreakNum(),getRoomInfo().getUserCardMap().get(player.getUserId()).size(),roomConfig.getScoreParam());
                addRankScore += result.getTotalPlus();
                winStreakNumPlus = result.getWinStreakNum();
                remainCardPlus = result.getRemainCardPlus();
            }else {
                // 失败
                reward = roomConfig.getDefeatReward();
                addRankScore = -levelConfig.getDefeatScore() * roomConfig.getScoreParam();
            }
            shuiHuYeZiCardModule.addRankScore(addRankScore);

            ShuiHuYeZiCardBattleRecordData battleRecordData = new ShuiHuYeZiCardBattleRecordData();
            battleRecordData.setActivityId(getRoomInfo().getActivityId());
            battleRecordData.setUserId(getRoomInfo().getUserId());
            battleRecordData.setRoomType(getRoomInfo().getRoomId());
            battleRecordData.setRemainCardNum(getRoomInfo().getUserCardMap().get(getRoomInfo().getUserId()).size());
            battleRecordData.setAddRankScore(addRankScore);
            battleRecordData.setCurRankScore(shuiHuYeZiCardModule.getUserData().getRankScore());
            battleRecordData.setReward(reward);
            battleRecordData.setIsWin(isWin);
            battleRecordData.setTargetRemainCardNum(getRoomInfo().getUserCardMap().get((long) (getRoomInfo().getRoomId())).size());
            battleRecordData.setStartTime(getRoomInfo().getStartTime());
            battleRecordData.setEndTime(DateHelper.getCurrentSecond());
            battleRecordData.setNpcId(getRoomInfo().getNpcId());
            battleRecordData.setInsertOption();
            shuiHuYeZiCardModule.addShuiHuYeZiCardBattleRecordData(battleRecordData);

            // 加奖励
            ShuiHuYeZiCardMgr.addReward(player, reward, eLogMoneyType.ShuiHuYeZiCardActivityPveEndGameReward);

            ShuiHuYeZiCardMgr.sendSettlement(3, player, isWin, reward, oldRankScore, shuiHuYeZiCardModule.getUserData().getRankScore(), shuiHuYeZiCardModule.getUserData().getPveWinningStreakNum(), winStreakNumPlus, remainCardPlus);

            // 加日志
            LogMgr.addLogShuiHuYeZiCardBattlerResultRecord(new LogShuiHuYeZiCardBattlerResultRecord(ShuiHuYeZiCardMgr.getActivityInfo().getActivityId(),
                    player.getUserId(), 0, getRoomInfo().getRoomId(), isWin, getRoomInfo().getAiModelIndex(),
                    oldRankScore, shuiHuYeZiCardModule.getUserData().getRankScore(), reward, getRoomInfo().getStartTime(),
                    DateHelper.getCurrentSecond()));

            // 清空房间信息
            getRoomInfo().setRoomId(0);
            getRoomInfo().setAiModelIndex(0);
            getRoomInfo().getUserCardMap().clear();
            getRoomInfo().setLastRoundWinnerId(0);
            getRoomInfo().setBuffId(0);
            getRoomInfo().setNum(0);
            getRoomInfo().getRecordList().clear();
            getRoomInfo().setNextBuffId(0);
            getRoomInfo().setRound(0);
            getRoomInfo().getDiscardList().clear();
            getRoomInfo().setStartTime(0);
            getRoomInfo().setNpcId(0);
            shuiHuYeZiCardModule.synUserData();

        }
    }


    /**
     * 计算出牌权重
     * @param playerCardMap 出牌方 拥有的卡牌
     * @param playerWeightMap 出牌的权重
     * @param targetCardMap 对方 拥有的卡牌
     * @param targetWeightMap 对方出牌的权重
     * @return
     */
    public Map<Integer,Integer> calPlayCardWeightMap(int type, Map<Integer, ShuiHuYeZiCardBattleCard> playerCardMap,Map<Integer,Integer> playerWeightMap,Map<Integer, ShuiHuYeZiCardBattleCard> targetCardMap ,Map<Integer,Integer> targetWeightMap){
        int minWeight = 0;
        // 是否有小于等于0的权重
        boolean flag = false;
        Map<Integer,Integer> map = new HashMap<>();
        for (ShuiHuYeZiCardBattleCard item : playerCardMap.values()){
            int weight = getPlayCardWeight(type,item,targetCardMap, targetWeightMap);
            map.put(item.getId(),weight);
            if(weight <= minWeight){
                minWeight = weight;
                flag = true;
            }
        }
        // 计算当前所有Wi的总和为Si
        int Si = 0;
        Map<Integer,Integer> tempWeightMap = new HashMap<>();
        for (Map.Entry<Integer,Integer> entry : map.entrySet()){
            int weight = entry.getValue();
            if(flag){
                weight = entry.getValue() - minWeight + 1;
            }
            Si += weight;
            tempWeightMap.put(entry.getKey(),weight);
        }
        //
        // 每个段位的AI 精准参赛
        int level = ShuiHuYeZiCardCommonMgr.getLevel(ShuiHuYeZiCardMgr.getConfig(),getRoomInfo().getRankScore());
        ShuiHuYeZiCardLevelConfig levelConfig = ShuiHuYeZiCardMgr.getConfig().getLevelConfigMap().get(level);
        int Sr = levelConfig.getAccuracyAI();
        for (Map.Entry<Integer,Integer> entry : tempWeightMap.entrySet()){
            int weight = 0;
            if(Sr == 0){
                weight = entry.getValue();
            }else {
                weight = entry.getValue() + (Si * getRandom().nextInt(Sr) / 1000);
            }
            playerWeightMap.put(entry.getKey(),weight);
        }
        return playerWeightMap;
    }

    /**
     * 计算要出的牌的权重
     * @param type           出牌人的类型 （0玩家 1npc）
     * @param card 要出的牌
     * @param targetCardMap 对手的牌
     * @param targetPlayWeightMap 对手每张牌的出牌权重
     * @return
     */
    private int getPlayCardWeight(int type ,ShuiHuYeZiCardBattleCard card, Map<Integer,ShuiHuYeZiCardBattleCard> targetCardMap, Map<Integer,Integer> targetPlayWeightMap){
        int Tp = 0;
        int Cp = 0;
        int Dp = 0;
        int X1 = ShuiHuYeZiCardMgr.getConfig().aiList.get(0);
        if(type == 0){
            Tp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(0);
            Cp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(1);
            Dp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(2);
        }else {
            List<Integer> tcdParamList = null;
            if(ShuiHuYeZiCardMgr.getConfig().tcdParamList.size() - 1 >= getRoomInfo().getAiModelIndex()){
                tcdParamList = ShuiHuYeZiCardMgr.getConfig().tcdParamList.get(getRoomInfo().getAiModelIndex());
                Tp = tcdParamList.get(0);
                Cp = tcdParamList.get(1);
                Dp = tcdParamList.get(2);
            }
            if(tcdParamList == null){
                // 增加容错
                Tp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(0);
                Cp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(1);
                Dp = ShuiHuYeZiCardMgr.getConfig().tcdList.get(2);
            }
        }
        // 输赢权重
        long totalWc = 0;
        // totalWi
        long totalWi = 0;
        for (ShuiHuYeZiCardBattleCard item : targetCardMap.values()){
            // 输赢权重
            int Wc = 0;
            if(card.getValue() > item.getValue()){
                // Cp
                Wc = Cp;
            }
            int Wi = targetPlayWeightMap.getOrDefault(item.getId(),10);
            totalWc += (Wc * Wi);
            totalWi += Wi;
        }
        // 点数权重
        long totalWd = 0;
        for (ShuiHuYeZiCardBattleCard item : targetCardMap.values()) {
            // 点数权重
            int Wd = 0;
            if (card.getValue() > item.getValue()) {
                // 赢
                Wd = Dp * (item.getValue() * 2 - card.getValue());
            }else {
                Wd = Dp * (item.getValue() - (card.getValue() * 2));
            }
            int Wi = targetPlayWeightMap.getOrDefault(item.getId(),10);
            totalWd += (Wd * Wi);
        }
        // 当前卡牌所属阵营
        int cardCampType = ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().get(card.getId()).getType();
        // 当前buff 作用的阵营
        int curBuffCampType = ShuiHuYeZiCardMgr.getConfig().getBuffConfigMap().get(getRoomInfo().getBuffId()).parList.get(1);
        // 下个buff 作用的阵营 有可能没有下一个buff
        ShuiHuYeZiCardBuffConfig nextBuffConfig = ShuiHuYeZiCardMgr.getConfig().getBuffConfigMap().get(getRoomInfo().getNextBuffId());
        int nextBuffCampType = 0;
        if(nextBuffConfig != null){
            nextBuffCampType = nextBuffConfig.parList.get(1);
        }
        // 战场权重
        long Wt = 0;
        if(cardCampType == curBuffCampType){
            Wt = Tp;
        }else if(cardCampType == nextBuffCampType){
            Wt = Tp * X1 / 1000L;
        }
        if(totalWi == 0){
            // 加个容错
            totalWi = 1;
            getLogger().error("水浒叶子牌 getPlayCardWeight 方法出现错误。 totalWi = 0  activityId:{}",ShuiHuYeZiCardMgr.getActivityInfo().getActivityId());
        }
        long Wi = ((totalWc + totalWd ) * 1000 + Wt * totalWi ) / (totalWi * 1000);
//        getLogger().info("当前buff阵营：{},下一个buff阵营：{}，输赢权重totalWc:{},点数权重totalWd：{},战场权重Wt:{},totalWi:{}",cardCampType,nextBuffCampType,totalWc,totalWd,Wt,totalWi);
//        getLogger().info("(0玩家 1npc )type:{},要出的牌：{}，npc当前的卡牌：{}，对手每张牌的出牌权重:{},最终计算出来的Wi:{}",type,card.getId(),targetCardMap.keySet(),targetPlayWeightMap,Wi);
        return (int)Wi;
    }

    /**
     * 选择ai模型
     */
    public int chooseAiModelIndex(ShuiHuYeZiCardModule shuiHuYeZiCardModule){
        int aiModelIndex = 0;
        if(getRoomInfo().getRoomId() == Integer.MAX_VALUE){
            aiModelIndex = getRandom().nextInt(ShuiHuYeZiCardMgr.getConfig().tcdParamList.size());
        }else {
            int level = ShuiHuYeZiCardCommonMgr.getLevel(ShuiHuYeZiCardMgr.getConfig(),getRoomInfo().getRankScore());
            ShuiHuYeZiCardLevelConfig levelConfig = ShuiHuYeZiCardMgr.getConfig().getLevelConfigMap().get(level);
            int Fr = levelConfig.getSucceedRate();

            ShuiHuYeZiCardWinOrLoseInfo shuiHuYeZiCardWinOrLoseInfo = shuiHuYeZiCardModule.getUserData().getLevelWinLoseMap().get(level);
            // 千分比
            int f = 500;
            if(shuiHuYeZiCardWinOrLoseInfo != null){
                f = shuiHuYeZiCardWinOrLoseInfo.winNum * 1000 / (shuiHuYeZiCardWinOrLoseInfo.loseNum + shuiHuYeZiCardWinOrLoseInfo.winNum);
            }
            boolean random = true;
            if(Math.abs(f - Fr) > ShuiHuYeZiCardMgr.getConfig().aiList.get(2)){
                int tempAiWinRate = 0;
                for (Map.Entry<Integer, ShuiHuYeZiCardWinOrLoseInfo> entry : shuiHuYeZiCardModule.getUserData().getAiWinLoseMap().entrySet()){
                    int winRate = entry.getValue().winNum * 1000 / (entry.getValue().loseNum + entry.getValue().winNum);
                    if(f > Fr){
                        // 选择Ai胜率最低的类型
                        if(aiModelIndex == 0 || winRate < tempAiWinRate){
                            aiModelIndex = entry.getKey();
                            tempAiWinRate = winRate;
                            random = false;
                        }
                    }else {
                        // 选择Ai胜率最高的类型
                        if(aiModelIndex == 0 || winRate > tempAiWinRate){
                            aiModelIndex = entry.getKey();
                            tempAiWinRate = winRate;
                            random = false;
                        }
                    }
                }
            }
            if(random){
                aiModelIndex = getRandom().nextInt(ShuiHuYeZiCardMgr.getConfig().tcdParamList.size());
            }
        }
        return aiModelIndex;
    }

    /**
     * 随机 ai手里的卡牌
     * @param shuiHuYeZiCardModule
     */
    private Map<Integer, ShuiHuYeZiCardUserCard> randomAiCardMap(ShuiHuYeZiCardModule shuiHuYeZiCardModule){
        List<ShuiHuYeZiCardCardConfig> list = new ArrayList(ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().values());
        Map<Integer, ShuiHuYeZiCardUserCard> aiCardMap = new HashMap<>();
        int level = ShuiHuYeZiCardCommonMgr.getLevel(ShuiHuYeZiCardMgr.getConfig(),shuiHuYeZiCardModule.getUserData().getRankScore());
        ShuiHuYeZiCardLevelConfig levelConfig = ShuiHuYeZiCardMgr.getConfig().getLevelConfigMap().get(level);
        // 金卡
        int goldNum = levelConfig.getGoldAI();
        if(goldNum > 0){
            Collections.shuffle(list);
            for (ShuiHuYeZiCardCardConfig item : list){
                if(goldNum-- == 0){
                    break;
                }
                ShuiHuYeZiCardUserCard card = aiCardMap.get(item.getId());
                if(card == null){
                    card = new ShuiHuYeZiCardUserCard();
                    card.setId(item.getId());
                    card.setNum(1);
                    aiCardMap.put(item.getId(),card);
                }
                card.setQuality(1);
            }
        }
        // 星级 总星级，就是随机20张卡，赋予等级，如果小于20 就直接随机，大于20小于40 就先每个1级，然后在随机..  就是保证最小星级和最大星级差不超过1就好了
        int starNum = levelConfig.getStarAI();
        if(starNum > 0){
            int totalCardNum = ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().size();
            int i = starNum / totalCardNum;
            if(i > 0){
                for (ShuiHuYeZiCardCardConfig item : list){
                    ShuiHuYeZiCardUserCard card = aiCardMap.get(item.getId());
                    if(card == null){
                        card = new ShuiHuYeZiCardUserCard();
                        card.setId(item.getId());
                        card.setNum(1);
                        aiCardMap.put(item.getId(),card);
                    }
                    card.setLevel(i);
                }
            }
            starNum -= totalCardNum * i;
            if(starNum > 0){
                Collections.shuffle(list);
                for (ShuiHuYeZiCardCardConfig item : list){
                    ShuiHuYeZiCardUserCard card = aiCardMap.get(item.getId());
                    if(card == null){
                        card = new ShuiHuYeZiCardUserCard();
                        card.setId(item.getId());
                        card.setNum(1);
                        aiCardMap.put(item.getId(),card);
                    }
                    card.setLevel(card.getLevel() + 1);
                    if(--starNum <= 0){
                        break;
                    }
                }
            }
        }
        return aiCardMap;
    }

    @Override
    public ShuiHuYeZiCardProto.ShuiHuYeZiCardRoomInfo.Builder builderShuiHuYeZiCardRoomInfo(long userId){
        Map<Long, PlayerProto.PlayerBaseTempMsg> userMap = new HashMap<>();
        userMap.put(getRoomInfo().getUserId(), PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(getRoomInfo().getUserId(), GameServer.getInstance().getServerId())).build());
        ShuiHuYeZiCardProto.ShuiHuYeZiCardRoomInfo.Builder roomInfo = ShuiHuYeZiCardCommonMgr.builderShuiHuYeZiCardRoomInfo(this,getRoomInfo().getUserCardMap(), 0, userMap,getRoomInfo().getRoomId());
        for (ShuiHuYeZiCardProto.ShuiHuYeZiCardUserBattleInfo.Builder builder : roomInfo.getBattleInfoListBuilderList()){
            if(builder.getUserId() == getRoomInfo().getUserId()){
                builder.setRankScore(getRoomInfo().getRankScore());
            }
        }
        return roomInfo;
    }

    /**
     * 创建引导所需的房间数据
     */
    public void creatGuideRoom(){
        // 练习模式 中的引导
        Map<Integer, ShuiHuYeZiCardBattleCard> cardMap1 = new HashMap<>();
        cardMap1.put(1,new ShuiHuYeZiCardBattleCard(1,0,0,0,false));
        cardMap1.put(8,new ShuiHuYeZiCardBattleCard(8,0,0,0,false));

        getRoomInfo().getUserCardMap().put(getRoomInfo().getUserId(), cardMap1);
        Map<Integer, ShuiHuYeZiCardBattleCard> cardMap2 = new HashMap<>();

        cardMap2.put(2,new ShuiHuYeZiCardBattleCard(2,0,0,0,false));
        cardMap2.put(3,new ShuiHuYeZiCardBattleCard(3,0,0,0,false));

        getRoomInfo().getUserCardMap().put((long)(getRoomInfo().getRoomId()), cardMap2);
        getRoomInfo().setBuffId(10001);
        getRoomInfo().setNum(3);

        getRoomInfo().setRound(1);
        getRoomInfo().setStartTime(DateHelper.getCurrentTime());

        // 创建弃牌堆
        for (ShuiHuYeZiCardCardConfig item : ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().values()) {
            for(Map<Integer, ShuiHuYeZiCardBattleCard> userCardMap : getRoomInfo().getUserCardMap().values()){
                if(userCardMap.keySet().contains(item.getId())){
                    continue;
                }
            }
            ShuiHuYeZiCardDiscardCard discardCard = new ShuiHuYeZiCardDiscardCard();
            discardCard.setId(item.getId());
            getRoomInfo().getDiscardList().add(discardCard);
        }

        refreshCard(ShuiHuYeZiCardMgr.getConfig());
    }

    /**
     * 菜鸟出牌
     */
    public ShuiHuYeZiCardBattleCard noobAutoPlayCard(){
        ShuiHuYeZiCardBattleCard playCard = null;
        // 1pve 三连败
        boolean isMustWin = false;
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(getRoomInfo().getUserId());
        ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
        List<ShuiHuYeZiCardBattleRecordData> list = shuiHuYeZiCardModule.getBattleRecordList(1,false);
        int loseStreakNum = 3;
        if(list != null && list.size() >= loseStreakNum) {
            // 三连败
            isMustWin = true;
            for (int i = list.size() - 1; i >= list.size() - loseStreakNum; i--) {
                if(list.get(i).getIsWin()){
                    isMustWin = false;
                    break;
                }
            }
//            if(isMustWin){
//                getLogger().info("叶子牌,三连败 触发必胜出牌，activityId:{},playerId{}",shuiHuYeZiCardModule.getUserData().getActivityId(),shuiHuYeZiCardModule.getUserData().getUserId());
//            }
        }
        if(!isMustWin){
            // 胜率过低
            int level = ShuiHuYeZiCardCommonMgr.getLevel(ShuiHuYeZiCardMgr.getConfig(),getRoomInfo().getRankScore());
            ShuiHuYeZiCardLevelConfig levelConfig = ShuiHuYeZiCardMgr.getConfig().getLevelConfigMap().get(level);
            ShuiHuYeZiCardWinOrLoseInfo levelWinOrLoseInfo = shuiHuYeZiCardModule.getUserData().getLevelWinLoseMap().get(level);
            if(levelWinOrLoseInfo == null){
                isMustWin = true;
//                getLogger().info("叶子牌,第一次到达该段位，胜率过低 触发必胜出牌，activityId:{},playerId{}",shuiHuYeZiCardModule.getUserData().getActivityId(),shuiHuYeZiCardModule.getUserData().getUserId());
            }else {
                int rate = levelWinOrLoseInfo.getWinNum() * 1000 / (levelWinOrLoseInfo.getLoseNum() + levelWinOrLoseInfo.getWinNum());
                if(rate < levelConfig.getSucceedRate()){
                    isMustWin = true;
//                    getLogger().info("叶子牌,胜率过低 触发必胜出牌，activityId:{},playerId{}，rate:{},level:{}",shuiHuYeZiCardModule.getUserData().getActivityId(),shuiHuYeZiCardModule.getUserData().getUserId(),rate,level);
                }
            }
        }
        if(isMustWin){
            // 必胜的出牌
            int p = 80;
            Map<Integer, ShuiHuYeZiCardBattleCard> npcCardMap = getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId()));
            int npcCardNum = npcCardMap.size();
            int playerCardNum = getRoomInfo().getUserCardMap().get(player.getUserId()).size();
            int diffCardNum = playerCardNum - npcCardNum;
            if(diffCardNum > 0){
                p = Math.max(1,p - diffCardNum * 5);
            }
            // 可以出的牌
            List<ShuiHuYeZiCardBattleCard> lessThanCardList = new ArrayList<>();
            List<ShuiHuYeZiCardBattleCard> moreThanCardList = new ArrayList<>();
            ShuiHuYeZiCardBattleCard bestCard = null;
            for (ShuiHuYeZiCardBattleCard item : npcCardMap.values()){
                if(item.getValue() < cardBattleCard.getValue()){
                    // 比玩家小的牌
                    lessThanCardList.add(item);
                }
                if(item.getValue() > cardBattleCard.getValue()){
                    // 比玩家大的牌
                    moreThanCardList.add(item);
                }
                if(bestCard == null || item.getValue() > bestCard.getValue()){
                    // 选择最大的卡牌
                    bestCard = item;
                }
            }
            playCard = bestCard;
            if(p > getRandom().nextInt(100)){
                // 判定输对方
                if(lessThanCardList.size() > 0){
                    playCard = lessThanCardList.get(getRandom().nextInt(lessThanCardList.size()));
                }
//                getLogger().info("判定输对方");
            }else {
                // 判定赢对方
                if(moreThanCardList.size() > 0){
                    playCard = moreThanCardList.get(getRandom().nextInt(moreThanCardList.size()));
                }
//                getLogger().info("判定赢对方");
            }
        }
//                getLogger().info("叶子牌,胜率过低 触发必胜出牌，activityId:{},playerId{},出的牌为cardId:{},p:{}",shuiHuYeZiCardModule.getUserData().getActivityId(),shuiHuYeZiCardModule.getUserData().getUserId(),playCard.getId(),p);
        return playCard;
    }


    /**
     * 引导房间指定出牌
     * @return
     */
    public ShuiHuYeZiCardBattleCard guideRoomPlayCard(){
        // 练习模式 中的引导
        ShuiHuYeZiCardBattleCard npcPlayCard = null;
        if(getRoomInfo().getRound() == 1){
            npcPlayCard = getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId())).get(3);
        }else if(getRoomInfo().getRound() == 2){
            npcPlayCard = getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId())).get(2);
        }else if(getRoomInfo().getRound() == 3){
            npcPlayCard = getRoomInfo().getUserCardMap().get((long)(getRoomInfo().getRoomId())).get(8);
        }
        return npcPlayCard;
    }

    /**
     * 是否是练习模式的引导房间
     * @return
     */
    public boolean isGuideRoom(){
        return getRoomInfo().getRoomId() == Integer.MAX_VALUE && isGuide;
    }
}
class PlayCardWeight{
    public int id;
    public int weight;

    public PlayCardWeight(int id, int weight) {
        this.id = id;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "PlayCardWeight{" +
                "id=" + id +
                ", weight=" + weight +
                '}';
    }
}
